package com.yj.web.controllers.admin;

import com.aliyuncs.exceptions.ClientException;
import com.yj.cache.service.YjCacheService;
import com.yj.passport.entity.UserPassport;
import com.yj.passport.service.PassportService;
import com.yj.web.annotation.LoginRequired;
import com.yj.web.dao.po.admin.*;
import com.yj.web.help.MsgSender;
import com.yj.web.model.BaseWebResult;
import com.yj.web.service.EmployeeService;
import com.yj.web.service.MessageService;
import com.yj.web.util.WebErrorCode;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by yanlinyang on 2017/6/28.
 */
@Controller
@RequestMapping("/admin")
public class EmployeeController extends BaseController {
    private static final Log logger = LogFactory.getLog(EmployeeController.class);

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private PassportService passportService;
    @Autowired
    private YjCacheService passportCache;
    @Autowired
    private MessageService messageService;

    @RequestMapping(value="/login", method = RequestMethod.POST)
    public @ResponseBody
    BaseWebResult login(@RequestParam("phone") String phone, @RequestParam("password") String password, @RequestParam("code") String code) {
        BaseWebResult result = new BaseWebResult();
        // TODO 此处要先验证手机号码
        if(StringUtils.isBlank(phone) || StringUtils.isBlank(password)) {
            result.setCd(1);
            result.setMsg("请输入手机号码和密码");
            return result;
        }

        Map<String, Object> resultMap = new HashMap<>();

        Employee employee = employeeService.loginByPhonePasswd(phone, password);
        if(employee == null) {
            result.setCd(1);
            result.setMsg("密码不对");
            return result;
        }
        resultMap.put("employee", employee);

        if (1 != employee.getIsActive()) {
            result.setCd(1);
            result.setMsg("该账户已关闭，如有疑问请您联系管理员");
            return result;
        }

        boolean res = employeeService.checkMsgCode(phone, code);
        if(!res) {
            result.setCd(1);
            result.setMsg("验证码不对");
            return result;
        }

        // 生成ticket，存入redis
        UserPassport userPassport = new UserPassport();
        userPassport.setUserId(employee.getId());
        String ticket = passportService.createPubTicket4Web(userPassport);
        userPassport.setTicket(ticket);
        resultMap.put("userPassport", userPassport);

        result.setMsg("正常:" + ticket);
        result.setData(resultMap);
        return result;
    }

    @RequestMapping(value="/sendCode", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult sendCode(@RequestParam("phone") String phone) {
        BaseWebResult result = new BaseWebResult();

        Employee employee = employeeService.findEmployeeByPhone(phone);
        if(employee == null) {
            result.setCd(1);
            result.setMsg("该用户不存在");
            return result;
        }

        // 1. 生成验证码
        String code = String.valueOf((int)((Math.random()*9+1) * 100000));

        // 2. 存入redis
        employeeService.setLoginKeyByMsg(phone, code);

        // 3. TODO 发送短信
        result.setMsg("验证码:" + code);

        String templateCode = "SMS_86670194";
        String templateParam = "{\"code\":\""+ code +"\"}";
        try {
            logger.debug("before sendCode to " + phone + result.getMsg());
            result = MsgSender.sendMsg(phone, templateCode, templateParam);
            logger.debug("after sendCode to " +phone + " result.msg: "+result.getMsg()+" result.data: "+result.getData());
        } catch (ClientException e) {
            logger.debug("catch exception during sendCode " + e);
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        String msgContent = "【医诺筹款】验证码："+code+"，您正在登录医诺筹款后台管理系统，如非本人操作，请忽略本短信";
        Message message = new Message();
        message.setReceiverStr(phone);
        Set<String> receivers = new HashSet<>();
        receivers.add(phone);
        message.setReceivers(receivers);
        message.setNumber(1);
        message.setContent(msgContent);
        message.setStatus(1);
        message.setType(2);
        messageService.insertMessage(message);
        return result;
    }

    @RequestMapping(value="/getInfoByToken", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult getInfoByToken(@RequestParam("token") String token) {
        BaseWebResult result = new BaseWebResult();
        Map<String, Object> info = new HashMap<>();
        try {
            long hostId = 0;
            UserPassport userPassport = null;
            userPassport = passportService.getPassportByTicket4Web(token);
            if (userPassport != null) {
                hostId = userPassport.getUserId();
            } else {
                result.setCd(WebErrorCode.E_SYS_NOT_LOGGED_IN);
//                result.setMsg("Token失效");
                return result;
            }
            Employee employee = employeeService.findEmployeeById(hostId);
            info.put("employee", employee);
            info.put("userPassport", userPassport);
            result.setData(info);
        } catch (Exception e) {
            result.setCd(1);
            result.setMsg("系统错误");
        }
        return result;
    }


    @LoginRequired
    @RequestMapping(value="/listEmployee", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult listEmployee(@RequestParam("name") String name,
                                                    @RequestParam("department") String department,
                                                    @RequestParam("phone") String phone,
                                                    @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "10") int size) {
        BaseWebResult result = new BaseWebResult();
        List<Employee> employees = null;
        try {
            employees = employeeService.listEmployee(name, department, phone, page, size);
        } catch (Exception e) {
            result.setCd(1);
            result.setMsg("系统错误");
        }
        result.setData(employees);
        return result;
    }

    @LoginRequired
    @RequestMapping(value="/createEmployee", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult createEmployee(@ModelAttribute("employee") Employee employee) {
        BaseWebResult result = new BaseWebResult();

        try {
            employeeService.createEmployee(employee);
            result.setMsg("增加成功");
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                result.setCd(1);
                result.setMsg("员工编号或手机号重复，请重新输入");
            } else {
                result.setCd(1);
                result.setMsg("系统错误");
            }
        }
        return result;
    }

    @LoginRequired
    @RequestMapping(value="/findEmployeeById", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult findInfoById(@RequestParam("id") long id) {
        BaseWebResult result = new BaseWebResult();
        if(id == 0) {
            result.setCd(1);
            result.setMsg("输入错误");
            return result;
        }
        Employee employee = employeeService.findEmployeeById(id);
        result.setData(employee);
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/updateEmployee", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult updateEmployee(@ModelAttribute("employee") Employee employee) {
        BaseWebResult result = new BaseWebResult();
        try {
            String msg = employeeService.updateEmployee(employee);
            result.setMsg(msg);
        } catch (Exception e) {
            result.setCd(1);
            result.setMsg("系统错误");
        }
        return result;
    }

//    @LoginRequired
//    @RequestMapping(value = "/deleteEmployee", method = RequestMethod.POST)
//    public @ResponseBody BaseWebResult deleteEmployee(@RequestParam("id") int id) {
//        BaseWebResult result = new BaseWebResult();
//        boolean b = employeeService.deleteEmployeeById(id);
//        if (!b) {
//            result.setCd(1);
//            result.setMsg("所要删除的员工不存在");
//        } else {
//            result.setMsg("删除成功");
//        }
//        return result;
//    }

    @LoginRequired
    @RequestMapping(value = "/countEmployee", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult countEmployee(@RequestParam("name") String name,
                                                     @RequestParam("department") String department,
                                                     @RequestParam("phone") String phone) {
        BaseWebResult result = new BaseWebResult();
        Integer num = employeeService.countEmployee(name, department, phone);
        result.setData(num);
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult resetPassword(@RequestParam("id") long id) {
        BaseWebResult result = new BaseWebResult();
        Employee employee = employeeService.findEmployeeById(id);
//        if (!DigestUtils.md5Hex(oldPWD).equals(employee.getPassword())) {
//            result.setCd(1);
//            result.setMsg("旧密码不对");
//        } else if (!newPWD1.equals(newPWD2)) {
//            result.setCd(1);
//            result.setMsg("输入的新密码不一致");
//        } else if (oldPWD.equals(newPWD1)) {
//            result.setCd(1);
//            result.setMsg("新密码不能与旧密码一样");
//        } else {
        employee.setPassword(DigestUtils.md5Hex("123456"));
        employeeService.resetPassword(employee);
        result.setMsg("新密码设置成功");
//        }
        return result;
    }

    //修改密码
    @LoginRequired
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult changePassword(@RequestParam("id") long id, @RequestParam("newPwd") String newPwd) {
        BaseWebResult result = new BaseWebResult();
        Employee employee = employeeService.findEmployeeById(id);
        if (DigestUtils.md5Hex(newPwd).equals(employee.getPassword())) {
            result.setCd(1);
            result.setMsg("新密码不能与旧密码一样");
        } else {
            employee.setPassword(DigestUtils.md5Hex(newPwd));
            employeeService.resetPassword(employee);
            result.setMsg("新密码设置成功");
        }
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/insertDuty", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult insertDuty(@RequestParam("name") String name) {
        BaseWebResult result = new BaseWebResult();
        int flag = 0;
        try {
            flag = employeeService.insertDuty(name);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                result.setCd(1);
                result.setMsg("已存在该名称");
                return result;
            }
        }
        if (0 == flag) {
            result.setCd(1);
            result.setMsg("插入失败");
        }
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/insertDepartment", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult insertDepartment(@RequestParam("name") String name) {
        BaseWebResult result = new BaseWebResult();
        long flag = employeeService.insertDepartment(name);
        if (0 == flag) {
            result.setCd(1);
            result.setMsg("插入失败");
        }
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/insertArea", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult insertArea(@RequestParam("name") String name) {
        BaseWebResult result = new BaseWebResult();
        long flag = employeeService.insertArea(name);
        if (0 == flag) {
            result.setCd(1);
            result.setMsg("插入失败");
        }
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/listDuty", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult listDuty() {
        BaseWebResult result = new BaseWebResult();
        List<Duty> duties = employeeService.listDuty();
        result.setData(duties);
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/listDepartment", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult listDepartment() {
        BaseWebResult result = new BaseWebResult();
        List<Department> departments = employeeService.listDepartment();
        result.setData(departments);
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/listArea", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult listArea() {
        BaseWebResult result = new BaseWebResult();
        List<Area> areas = employeeService.listArea();
        result.setData(areas);
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/listManager", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult listManager() {
        BaseWebResult result = new BaseWebResult();
        List<Employee> managers = employeeService.listManager();
        result.setData(managers);
        return result;
    }

    @LoginRequired
    @RequestMapping(value = "/updateEmployeeStatus", method = RequestMethod.POST)
    public @ResponseBody BaseWebResult updateEmployeeStatus(@RequestParam("id") long id, @RequestParam("isActive") int isActive) {
        BaseWebResult result = new BaseWebResult();
        try {
            boolean flag = employeeService.updateEmployeeStatus(id, isActive);
            if (false == flag) {
                result.setCd(1);
                result.setMsg("系统错误");
            } else {
                result.setMsg("状态更新成功");
            }
        } catch (Exception e) {
            result.setCd(1);
            result.setMsg("系统错误");
        }
        return result;
    }
}
